package com.boot.main.exception;

import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass){
        // return methodParameter.getDeclaringClass().isAssignableFrom(BasicErrorController.class);
         return true;
    }
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse){
        if(serverHttpRequest.getURI().getPath().startsWith("/swagger") || serverHttpRequest.getURI().getPath().startsWith("/v2/api-docs")){
            return body;
        }
        if(mediaType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)){
            if(body instanceof ResponseData){
                ResponseData responseData = (ResponseData) body;
                if(responseData.getCode() != 200){
                    serverHttpResponse.setStatusCode(HttpStatus.valueOf(responseData.getCode()));
                }
                return body;
            }else {
                serverHttpResponse.setStatusCode(HttpStatus.valueOf(400));
                return ResponseDataUtil.response(400, "未知错误！", body);
            }
        }
        return body;
    }
}
